import { getStoreList, getTree, goodsQuery } from '@mall/api/good'
import { getNearStore, getStoreDetail } from "@mall/api/store"
import router from "@src/router";
import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import mall from "@src/store/mall";
import base from "@src/store/base"

Component({
  behaviors: [storeBindingsBehavior],
  storeBindings: [{
    store: mall,
    fields: {
      'curLocation': "curLocation",
      "curStoreId": "storeId"
    },
    actions: ['initLocation', 'setStoreId']
  }, {
    store: base,
    fields: ['barHeight']
  }],
  data: {
    title: '搜索',
    loading: true,
    //商品列表
    goodsList: [],
    pageNum: 1,
    pageSize: 10,
    hasNextPage: true,
    storeId: null,
    storeName: "",
    filterForm: {},
    keyword: "",
    storeList: [],
    categoryTree: [],
    isLoading: true,
  },
  methods: {
    onLoad(options) {
      let storeId = options.storeId
      if (storeId) {
        let filterForm = { "buyWay": { value: ["", storeId] } }
        this.setData({ storeId, filterForm })
        getStoreDetail({ storeId }).then(res => {
          console.log('门店信息--',res)
          this.setData({ storeName: res.data.name })
        })
      }
    },
    onLogin() {
      if (!this.data.curStoreId) {
        // 获取定位, 获取最近门店
        this.initLocation().then(res => {
          let params = { latitude: res.latitude, longitude: res.longitude }
          this.fetchNearStore(params)
        }).catch(error => {
          console.log('error', error)
          this.fetchNearStore();
        });
      }
      this.fetchGoodsList();
      this.fetchStores();
      this.fetchCategoryTree();
    },
    fetchStores: function () {
      let data = {};
      getStoreList(data).then(res => {
        this.setData({ storeList: res.data })
      })
    },
    fetchCategoryTree() {
      getTree().then(res => {
        if (res.code === 0) {
          this.setData({ categoryTree: res.data })
        }
      })
    },
    //获取门店信息
    fetchNearStore(temp) {
      getNearStore(temp).then(res => {
        if (res.code === 0) {
          this.setStoreId(res.data.storeId);
          this.updateStoreBindings();
        }
      })
    },
    fetchGoodsList() {
      if (!this.data.hasNextPage) {
        return;
      }
      let params = {
        pageNum: this.data.pageNum,
        pageSize: this.data.pageSize,
      }
      if (this.data.keyword) {
        params['keyword'] = this.data.keyword
      }

      let filterForm = this.data.filterForm
      if (filterForm) {
        console.log("filterForm", filterForm)
        // 筛选条件
        if (filterForm["sort"] != null) {
          params['sort'] = filterForm["sort"].value
        }
        if (filterForm["category"] != null) {
          params['categoryIds'] = [filterForm["category"].value[filterForm["category"].value.length - 1]]
        }
        if (filterForm["buyWay"] != null) {
          let buyWay = filterForm["buyWay"].value;
          if (buyWay.length > 1 && buyWay[1]) {
            params['storeId'] = buyWay[1]
          }
          if (buyWay.length > 0 && buyWay[0]) {
            params['deliveryType'] = buyWay[0]
          }
        }
      }
      goodsQuery(params).then(res => {
        if (res.code === 0) {
          if (this.data.pageNum !== params.pageNum) {
            // 页面已经变化
            return;
          }
          let goodsList = this.data.goodsList
          if (params.pageNum === 1) {
            goodsList = []
          }
          this.setData({
            loading: false,
            goodsList: goodsList.concat(res.data.list) || [],
            hasNextPage: res.data.hasNextPage
          })
        }
      }).catch(err => {
        this.setData({ loading: false })
      })
    },

    handleFilter(e) {
      console.info("handleFilter")
      this.setData({ filterForm: e.detail, hasNextPage: true, pageNum: 1 })
      this.fetchGoodsList();
    },
    handleSearch(e) {
      this.setData({ keyword: e.detail, hasNextPage: true, pageNum: 1 })
      this.fetchGoodsList();
    },

    //进入详情页
    handleToGoods(e) {
      let goods = e.currentTarget.dataset.item
      let storeId = this.data.curStoreId;
      if (goods.skuInfo) {
        storeId = goods.skuInfo.storeId
      }
      if (storeId == null) {
        // 获取最近门店
        this.fetchNearStore()
        return;
      }

      let urlParams = {
        storeId: storeId,
        goodsSerial: goods.goodsSerial
      };

      router.push({ name: "mall/goods-detail", params: urlParams })
    },
    noMake() {
      return true;
    },
    onReachBottom() {
      console.log("触底了")
      if (this.data.hasNextPage) {
        let pageNum = this.data.pageNum + 1
        this.setData({ pageNum: pageNum })
        this.fetchGoodsList()
      }
    },
  }
})
